package com.aj.activity.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aj.activity.R;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.AccountDao;
import com.aj.databases.entry.Account;
import com.aj.databases.entry.FamilyZoneInfo;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.AlbumManagerRequest;
import com.aj.http.request.GetAlbumPhotoRequest;
import com.aj.http.request.UploadPhotoRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.GetAlbumPhotoResponse;
import com.aj.http.response.UploadPhotoResponse;
import com.aj.utils.Contants;
import com.aj.utils.PortraitLoaderUtil;

public class FamilyPhotoFragment extends FamilyBaseFragment {

    private GridView mGridView;
    private LinearLayout person_photo_bottom;
    private TextView update_name_text;
    private TextView delete_text;
    private TextView delete_all_text;
    private Button sure_or_cannelbutton;
    private Account account;
    private EditText albumCover;

    private FamilyPhotoAdapter familyPhotoAdapter;

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        reregisterRefreshReceiver();
        View view = inflater.inflate(R.layout.family_photo_fragment, null, false);
        mGridView = (GridView) view.findViewById(R.id.family_photo_body);
        person_photo_bottom = (LinearLayout) view.findViewById(R.id.family_photo_bottom);
        update_name_text = (TextView) view.findViewById(R.id.update_name_text);
        delete_text = (TextView) view.findViewById(R.id.delete_text);
        delete_all_text = (TextView) view.findViewById(R.id.delete_all_text);
        sure_or_cannelbutton = (Button) view.findViewById(R.id.sure_or_cannelbutton);
        initGridView();
        return view;
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterRefreshReceiver();
    }

    private void reregisterRefreshReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contants.REFRESH_PERSION_ALBUM_ACTION);
        filter.setPriority(Integer.MAX_VALUE);
        getActivity().registerReceiver(refreshReceiver, filter);
    }

    private void unregisterRefreshReceiver() {
        getActivity().unregisterReceiver(refreshReceiver);
    }

    private BroadcastReceiver refreshReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            initGridView();
        }
    };

    private void initGridView() {
        showProgressDialog();
        final AccountDao accountDao = new AccountDao(getActivity());
        account = accountDao.getByToken(LoveHomeApplication.token);

        // 4为家庭相册
        new GetAlbumPhotoRequest().excute(getActivity(), account.getLast_used_user_id(), "4", 50, 0, new IHttpCallBack() {
            @Override
            public void success(String result) {
                dimissProgressDialog();
                try {
                    GetAlbumPhotoResponse getAlbumPhotoResponse = new GetAlbumPhotoResponse(new JSONObject(result));
                    List<FamilyZoneInfo> familyZoneInfoList = getAlbumPhotoResponse.getAlbumPhotoInfoList();
                    if (familyZoneInfoList == null) {
                        familyZoneInfoList = new ArrayList<FamilyZoneInfo>();
                    }
                    FamilyZoneInfo familyZoneInfo = new FamilyZoneInfo();
                    familyZoneInfo.setItemSelected(false);
                    familyZoneInfo.setZoneName(getString(R.string.familyspace_newphoto_text));
                    familyZoneInfoList.add(familyZoneInfo);
                    familyPhotoAdapter = new FamilyPhotoAdapter(getActivity(), familyZoneInfoList);
                    mGridView.setAdapter(familyPhotoAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String result) {
                dimissProgressDialog();
            }
        });

    }

    class FamilyPhotoAdapter extends BaseAdapter {

        private boolean isManagerment = false;
        private List<FamilyZoneInfo> data;
        private LayoutInflater mInflater;
        private Context context;
        private HashMap<Integer, View> viewCache = new HashMap<Integer, View>();

        public FamilyPhotoAdapter(Context context, List<FamilyZoneInfo> data) {
            this.context = context;
            this.data = data;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public List<FamilyZoneInfo> getFamilyZoneInfoList() {
            return data;
        }

        public void update(List<FamilyZoneInfo> familyZoneInfoList) {
            data = familyZoneInfoList;
            notifyDataSetChanged();
        }

        public void updateManagerment(boolean managerment) {
            isManagerment = managerment;
            notifyDataSetChanged();
        }

        class ViewHodler {
            ImageView family_albums_image;
            TextView family_albums_name;
            CheckBox family_albums_checkbox;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            convertView = viewCache.get(position);
            final ViewHodler viewHodler;
            final FamilyZoneInfo familyZoneInfo = data.get(position);
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_person_albums, null);
                viewHodler = new ViewHodler();
                viewHodler.family_albums_image = (ImageView) convertView.findViewById(R.id.person_albums_image);
                viewHodler.family_albums_name = (TextView) convertView.findViewById(R.id.person_albums_name);
                viewHodler.family_albums_checkbox = (CheckBox) convertView.findViewById(R.id.person_albums_checkbox);
                convertView.setTag(viewHodler);
                viewCache.put(position, convertView);
            } else {
                viewHodler = (ViewHodler) convertView.getTag();
            }
            String photonameString = familyZoneInfo.getZoneName();
            if (familyZoneInfo.getZoneId() != null) {
                viewHodler.family_albums_name.setText(photonameString + "(" + familyZoneInfo.getPhotoNumber() + ")");
                PortraitLoaderUtil.loadSrc(context, viewHodler.family_albums_image, null, familyZoneInfo.getZoneUrl(), R.drawable.nomal_photo,
                        R.drawable.nomal_photo);
            } else {
                viewHodler.family_albums_name.setText(photonameString);
            }

            if (isManagerment && position != (data.size() - 1)) {
                viewHodler.family_albums_checkbox.setVisibility(View.VISIBLE);
            } else {
                viewHodler.family_albums_checkbox.setVisibility(View.GONE);
                viewHodler.family_albums_checkbox.setChecked(false);
                familyZoneInfo.setItemSelected(false);
            }

            viewHodler.family_albums_image.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (isManagerment) {
                        if (viewHodler.family_albums_checkbox.isChecked()) {
                            viewHodler.family_albums_checkbox.setChecked(false);
                            familyZoneInfo.setItemSelected(false);
                        } else {
                            viewHodler.family_albums_checkbox.setChecked(true);
                            familyZoneInfo.setItemSelected(true);
                        }
                    } else {
                        if (position != (data.size() - 1)) {
                            Intent intent = new Intent(Contants.PERSONLUPLOADALBUM_ACTIVITY_ACTION);
                            intent.putExtra(Contants.PAGEFLAG_STRING, Contants.ALBUM_TYPE_SELF);
                            intent.putExtra(Contants.TITLE_PARAMS, familyZoneInfo.getZoneName());
                            intent.putExtra(Contants.USER_ID_PARAMS, account.getLast_used_user_id());
                            intent.putExtra(Contants.ZONE_ID_PARAMS, familyZoneInfo.getZoneId());
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(Contants.NEWPHOTOALBUM_ACTIVITY_ACTION);
                            intent.putExtra(Contants.ALBUMORZONE_PARAMS, Contants.FAMILY_ALBUM_TYPE);
                            intent.putExtra(Contants.USER_ID_PARAMS, account.getLast_used_user_id());
                            startActivity(intent);
                        }
                    }

                }
            });

            viewHodler.family_albums_image.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    if (!isManagerment) {
                        updateManagerment(true);
                        createBottomMenu();
                    }
                    return false;
                }
            });

            if (position == (data.size() - 1)) {
                viewHodler.family_albums_image.setImageResource(R.drawable.add_photo_button);
            }
            return convertView;

        }
    }

    private void createBottomMenu() {
        person_photo_bottom.setVisibility(View.VISIBLE);
        Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.dialog_enter);
        person_photo_bottom.startAnimation(anim);

        ButtonClick buttonClick = new ButtonClick();
        update_name_text.setOnClickListener(buttonClick);
        delete_text.setOnClickListener(buttonClick);
        delete_all_text.setOnClickListener(buttonClick);
        sure_or_cannelbutton.setOnClickListener(buttonClick);

    }

    class ButtonClick implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.update_name_text:
                if (hasPhotoSelected()) {
                    createModifyDialog();
                } else {
                    Toast.makeText(getActivity(), getString(R.string.album_not_choose_text), Toast.LENGTH_LONG).show();
                }

                break;
            case R.id.delete_text:
                if (hasPhotoSelected()) {
                    createDeleteDialog();
                } else {
                    Toast.makeText(getActivity(), getString(R.string.album_not_choose_text), Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.delete_all_text:
                createDeleteAllDialog();
                break;
            case R.id.sure_or_cannelbutton:
                closePanel();
                break;
            default:
                break;
            }
        }
    }
    
    private void createDeleteAllDialog() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.delete_dialog_layout, null);
        // 对话框
        final Dialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);

        TextView dialog_content = (TextView) layout.findViewById(R.id.dialog_content);
        dialog_content.setText(getString(R.string.delete_all_album_alert_text));

        Button okButton = (Button) layout.findViewById(R.id.sure_button);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<FamilyZoneInfo> datas = familyPhotoAdapter.getFamilyZoneInfoList();
                String albumIdArray = "";
                for (FamilyZoneInfo info : datas) {
                    if (info.getZoneId() != null) {
                        albumIdArray += info.getZoneId() + ",";
                    }
                }
                albumIdArray = albumIdArray.substring(0, albumIdArray.lastIndexOf(","));
                deleteFamilyAlbum(albumIdArray);
                dialog.dismiss();
            }
        });
        Button cancelButton = (Button) layout.findViewById(R.id.cannel_button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    
    

    private boolean hasPhotoSelected() {
        List<FamilyZoneInfo> datas = familyPhotoAdapter.getFamilyZoneInfoList();
        for (FamilyZoneInfo info : datas) {
            if (info.isItemSelected()) {
                return true;
            }
        }
        return false;

    }
    
    private void deleteFamilyAlbum(String albumId) {
        showProgressDialog();
        AlbumManagerRequest request = new AlbumManagerRequest();
        request.excute(getActivity(), account.getLast_used_user_id(), "3", albumId, null, null, null, "4", new IHttpCallBack() {
            @Override
            public void success(String result) {
                closePanel();
                initGridView();
                dimissProgressDialog();
            }

            @Override
            public void fail(String result) {
                try {
                    Common common = new Common(new JSONObject(result));
                    Toast.makeText(getActivity(), common.getErrorMsg(), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dimissProgressDialog();
                closePanel();
            }
        });
    }

    private void createDeleteDialog() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.delete_dialog_layout, null);
        // 对话框
        final Dialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);

        Button okButton = (Button) layout.findViewById(R.id.sure_button);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<FamilyZoneInfo> datas = familyPhotoAdapter.getFamilyZoneInfoList();
                for (FamilyZoneInfo info : datas) {
                    if (info.isItemSelected()) {
                        deleteFamilyAlbum(info.getZoneId());
                        dialog.dismiss();
                    }
                }
            }
        });
        Button cancelButton = (Button) layout.findViewById(R.id.cannel_button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    
    
    private void modifyFamilyAlbum(final String albumId, final String albumName, final String albumDesc, String filePath) {
        showProgressDialog();
        final File file = new File(filePath);
        showProgressDialog(getString(R.string.local_update_load_text));
        UploadPhotoRequest uploadPhotoRequest = new UploadPhotoRequest();
        uploadPhotoRequest.excute(getActivity(), null, null, "JPEG", file, new IHttpCallBack() {

            @Override
            public void success(String result) {
                try {
                    UploadPhotoResponse updatePhotoResponse = new UploadPhotoResponse(new JSONObject(result));
                    Common common = updatePhotoResponse.getCommon();
                    if (common != null && common.getReturnCode().equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {

                        AlbumManagerRequest request = new AlbumManagerRequest();
                        request.excute(getActivity(), account.getLast_used_user_id(), "2", albumId, albumName, albumDesc,
                                updatePhotoResponse.getPhotoUrl(), "4", new IHttpCallBack() {
                                    @Override
                                    public void success(String result) {
                                        closePanel();
                                        initGridView();
                                        dimissProgressDialog();
                                    }

                                    @Override
                                    public void fail(String result) {
                                        try {
                                            Common common = new Common(new JSONObject(result));
                                            Toast.makeText(getActivity(), common.getErrorMsg(), Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        dimissProgressDialog();
                                        closePanel();
                                    }
                                });
                    } else {
                        dimissProgressDialog();
                        Toast.makeText(getActivity(), common.getErrorMsg(), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e1) {
                    dimissProgressDialog();
                    closePanel();
                    e1.printStackTrace();
                }

            }

            @Override
            public void fail(String result) {
                dimissProgressDialog();
                closePanel();
                try {
                    UploadPhotoResponse updatePhotoResponse = new UploadPhotoResponse(new JSONObject(result));
                    Common common = updatePhotoResponse.getCommon();
                    Toast.makeText(getActivity(), common.getErrorMsg(), Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        });

    }
    

    private void createModifyDialog() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.modify_dialog_layout, null);
        // 对话框
        final AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setView(inflater.inflate(R.layout.modify_dialog_layout, null));
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);

        final EditText albumName = (EditText) layout.findViewById(R.id.enter_albumname);
        albumCover = (EditText) layout.findViewById(R.id.enter_album_cover);
        final EditText albumDescription = (EditText) layout.findViewById(R.id.enter_albumdescription);
        ImageView cover_image = (ImageView) layout.findViewById(R.id.cover_image);
        cover_image.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);
            }
        });

        Button okButton = (Button) layout.findViewById(R.id.sure_button);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (albumName.getText().toString().trim().length() == 0) {
                    Toast.makeText(getActivity(), getString(R.string.newalbum_name_alert_text), Toast.LENGTH_LONG).show();
                    return;
                }

                if (albumDescription.getText().toString().trim().length() == 0) {
                    Toast.makeText(getActivity(), getString(R.string.newalbum_desc_alert_text), Toast.LENGTH_LONG).show();
                    return;
                }

                List<FamilyZoneInfo> datas = familyPhotoAdapter.getFamilyZoneInfoList();
                for (FamilyZoneInfo info : datas) {
                    if (info.isItemSelected()) {
                        String albumNameStr = albumName.getText().toString().trim();
                        String albumDescriptionStr = albumDescription.getText().toString().trim();
                        String filePath = albumCover.getText().toString().trim();
                        modifyFamilyAlbum(info.getZoneId(), albumNameStr, albumDescriptionStr, filePath);
                        dialog.dismiss();
                    }
                }
            }
        });
        Button cancelButton = (Button) layout.findViewById(R.id.cannel_button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode) {
            if ((data != null) && (requestCode == 2)) {
                // Object object = data.getExtras().get("data");
                // ContentResolver resolver = getContentResolver();
                // pictureResult(data);
                Uri originalUri = data.getData(); // 获得图片的uri
                // bm = MediaStore.Images.Media.getBitmap(resolver,
                // originalUri); // 显得到bitmap图片
                String[] proj = { MediaStore.Images.Media.DATA };
                // 好像是android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = getActivity().getContentResolver().query(originalUri, proj, null, null, null);
                // 按我个人理解 这个是获得用户选择的图片的索引值
                int column_index = cursor.getColumnIndex(proj[0]);
                // 将光标移至开头 ，这个很重要，不小心很容易引起越界
                if (cursor.moveToFirst()) {
                    // 最后根据索引值获取图片路径
                    String filePath = cursor.getString(column_index);
                    albumCover.setText(filePath);
                    cursor.close();
                }
            }
        }
    }

    private void closePanel() {
        Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.dialog_exit);
        anim.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                person_photo_bottom.setVisibility(View.GONE);
                familyPhotoAdapter.updateManagerment(false);
            }
        });
        person_photo_bottom.startAnimation(anim);
    }
}
